package com.hemerasolutions.v2trainer.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;

import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.hemerasolutions.v2trainer.component.interfaces.table.EquipmentTableCompInterface;
import com.hemerasolutions.v2trainer.controller.interfaces.PersonalTrainerBeanInterface;
import com.hemerasolutions.v2trainer.model.multimedia.Photo;
import com.hemerasolutions.v2trainer.model.users.PersonalTrainer;
import com.hemerasolutions.v2trainer.model.users.User;
import com.hemerasolutions.v2trainer.service.ExceptionService;
import com.hemerasolutions.v2trainer.service.interfaces.LibraryServiceInterface;
import com.hemerasolutions.v2trainer.service.interfaces.UserServiceInterface;


@Controller
@ManagedBean(name="personalTrainerBean")
@Scope("view")
public class PersonalTrainerBean extends BaseBean implements PersonalTrainerBeanInterface {

	private static final long serialVersionUID = 1L;

	@Autowired
	private UserServiceInterface userService;
	
	@Autowired
	private LibraryServiceInterface libraryService;
	
	@Autowired
	private EquipmentTableCompInterface equipmentTable;
	
	private List<PersonalTrainer> personalTrainers;
	
	private PersonalTrainer selPersonalTrainer;
	
	private PersonalTrainer personalTrainer;
	
	private int uploadType;
	
	private Date 		begCreatedAt;
    
	private Date 		endCreatedAt;
    
	private Date 		begChangedAt;
    
	private Date 		endChangedAt;

	private Date 		begExpireOn;
    
	private Date 		endExpireOn;
	
	private String 		findByName;
    
	private String 		findByLastName;

	private String 		findByCnpj;
    
	private String 		findByCpf;

	private String 		findByEmail;
    
	private boolean 	findByStatus = true;	
	
	public PersonalTrainerBean() {
		super();
	}

	@PostConstruct
	public void init(){
		super.init();

		if(this.getActiveUserType() == User.USERTYPE_PT){
			this.personalTrainer = this.getActiveActor(PersonalTrainer.class);
			this.equipmentTable.setEquipments(this.personalTrainer.getEquipments());	
			this.equipmentTable.refresh();				
		}else{
			this.listAll();
		}
	}
	

	
	
	private void listAll() {

	   	Map<String,Object> fields = new HashMap<String, Object>();
	    this.personalTrainers = this.userService.searchPersonalTrainers(fields);

	}	
	
	public void clear(){
		this.personalTrainer = null;
	}
	
	public void createPersonalTrainer(){
		try {
			userService.createPersonalTrainer(personalTrainer);
			this.showInfoMessage(	this.localizedText("CreatedWithSuccess"),
					this.localizedText("ThePersonalTrainer") + " " +
					this.personalTrainer.getFirstName() + "\n " + 
					this.localizedText("wasCreatedWithSuccess"));			
			this.personalTrainer = null;
			this.listAll();
		} catch (ExceptionService e) {
			this.showErrorMessage(this.localizedText("CreateError"), e.getLocalizedMessage());
			e.printStackTrace();
		}
	}
	
	
	public void savePersonalTrainer(){
		try {
			userService.savePersonalTrainer(personalTrainer);
			this.showInfoMessage(	this.localizedText("SavedWithSuccess"),
					this.localizedText("ThePersonalTrainer") + " " +
					this.personalTrainer.getFirstName() + "\n " + 
					this.localizedText("wasSavedWithSuccess"));			
			this.personalTrainer = null;
			this.listAll();
		} catch (ExceptionService e) {
			this.showErrorMessage(this.localizedText("SaveError"), e.getLocalizedMessage());
		}
	}
	
	public void cancelChange(){
		if(this.personalTrainer.getId() != 0){
			this.personalTrainer = userService.readPersonalTrainer(personalTrainer);
		}else{
			this.personalTrainer = new PersonalTrainer();
		}
	}

	public void uploadPhoto(FileUploadEvent ev){
		
		if(this.uploadType == 1){		

			Photo photo = new Photo();

			photo.setName("default_logo");
			photo.setHeight(120);
			photo.setWidth(100);
			
			personalTrainer.setLogo(super.uploadPhoto(ev, photo));
			personalTrainer.setLogo(userService.savePhoto(photo));

		}else if (this.uploadType == 2){

			Photo photo = new Photo();

			photo.setName("default_wide_logo");
			photo.setHeight(80);
			photo.setWidth(250);
			
			personalTrainer.setWideLogo(super.uploadPhoto(ev, photo));
			personalTrainer.setWideLogo(userService.savePhoto(photo));

		}else if (this.uploadType ==3){
			Photo photo = new Photo();

			photo.setName("user_photo");
			photo.setHeight(120);
			photo.setWidth(100);
			
			personalTrainer.setPhoto(super.uploadPhoto(ev, photo));
			personalTrainer.setPhoto(userService.savePhoto(photo));
			
		}
	}
	
	public void search(ActionEvent event){

    	Map<String,Object> fields = new HashMap<String, Object>();
    	
		if( this.begCreatedAt != null && this.endCreatedAt != null && 
				this.begCreatedAt.compareTo(this.endCreatedAt) > 0){
				this.showErrorMessage(	this.localizedText("CreationDate"),
										this.localizedText("TheInitialDateNeedToBeGreaterThanFinal"));
				return;
			}
			

		if( this.begChangedAt != null && this.endChangedAt != null && 
			this.begChangedAt.compareTo(this.endChangedAt) > 0){
			this.showErrorMessage(	this.localizedText("ChangeDate"),
									this.localizedText("TheInitialDateNeedToBeGreaterThanFinal"));
			return;			
		}

		if( this.begExpireOn != null && this.endExpireOn != null && 
				this.begExpireOn.compareTo(this.endExpireOn) > 0){
				this.showErrorMessage(	this.localizedText("ExpireDate"),
										this.localizedText("TheInitialDateNeedToBeGreaterThanFinal"));
				return;
			}
		
    	

    	if (!this.findByName.equals("")) {
            fields.put("firstName", this.findByName);
        }

    	if (!this.findByName.equals("")) {
            fields.put("lastName", this.findByName);
        }

    	
    	if (!this.findByEmail.equals("")){
    		fields.put("email",this.findByEmail);
    	}
    	
    	if (!this.findByCnpj.equals("")){
    		fields.put("cnpj",this.findByCnpj);
    	}
    	
    	if (this.begCreatedAt != null){
    		fields.put("begCreatedAt", this.begCreatedAt);
    	}
    	if (this.endCreatedAt != null){
            fields.put("endCreatedAt",this.endCreatedAt);
        }
        if (this.begChangedAt != null){
        	fields.put("begChangedAt",this.begChangedAt);
        }
        if (this.endChangedAt != null){
        	fields.put("endChangedAt", this.endChangedAt);
        }

        if (this.begExpireOn != null){
        	fields.put("begExpireOn",this.begExpireOn);
        }
        if (this.endExpireOn != null){
        	fields.put("endExpireOn", this.endExpireOn);
        }
        
        
	    fields.put("active", this.findByStatus);
		
	    this.personalTrainers = this.userService.searchPersonalTrainers(fields);

		if((this.personalTrainers).isEmpty()){
			this.showInfoMessage(	this.localizedText("SearchCompleted"),
									this.localizedText("NoEntrysFounded"));
		}else{
			this.showInfoMessage(	this.localizedText("SearchCompleted"),
									this.personalTrainers.size() + " " + 
									this.localizedText("entrysFounded"));
		}
	}
	

	
	public void deletePersonalTrainer(){
		
		try{
			userService.deletePersonalTrainer(personalTrainer);
			this.showInfoMessage(	this.localizedText("Deleted"),
									this.localizedText("UserDeletedWithSuccess"));
			this.personalTrainers.remove(this.personalTrainer);
			this.personalTrainer = null;
			
		}catch(ExceptionService e){
			this.showErrorMessage(this.localizedText("DeleteError"),
					e.getLocalizedMessage());
		}
	}
	
	
	public void toAddPersonalTrainer(){
		this.personalTrainer  = new PersonalTrainer();
		
		this.personalTrainer.setLogo(userService.copyDefaultLogo());
		this.personalTrainer.setWideLogo(userService.copyDefaultWideLogo());
		this.personalTrainer.setPhoto(userService.copyDefaultUserPhoto());
		this.personalTrainer.getUser().setLibrarys(libraryService.copyPublicLibrarys());
		
		this.equipmentTable.setEquipments(this.personalTrainer.getEquipments());	
		this.equipmentTable.refresh();
		
		
	}
	
	public void toViewPersonalTrainer(){

		this.equipmentTable.setEquipments(this.personalTrainer.getEquipments());	
		this.equipmentTable.refresh();		
	}
	
	public List<PersonalTrainer> getPersonalTrainers() {
		return personalTrainers;
	}

	public PersonalTrainer getSelPersonalTrainer() {
		return selPersonalTrainer;
	}

	public PersonalTrainer getPersonalTrainer() {
		return personalTrainer;
	}

	public void setPersonalTrainers(List<PersonalTrainer> personalTrainers) {
		this.personalTrainers = personalTrainers;
	}

	public void setSelPersonalTrainer(PersonalTrainer selPersonalTrainer) {
		this.selPersonalTrainer = selPersonalTrainer;
	}

	public void setPersonalTrainer(PersonalTrainer personalTrainer) {
		this.personalTrainer = personalTrainer;
	}

	public int getUploadType() {
		return uploadType;
	}

	public void setUploadType(int uploadType) {
		this.uploadType = uploadType;
	}


	public Date getBegCreatedAt() {
		return begCreatedAt;
	}

	public Date getEndCreatedAt() {
		return endCreatedAt;
	}

	public Date getBegChangedAt() {
		return begChangedAt;
	}

	public Date getEndChangedAt() {
		return endChangedAt;
	}

	public String getFindByName() {
		return findByName;
	}

	public String getFindByCnpj() {
		return findByCnpj;
	}

	public String getFindByEmail() {
		return findByEmail;
	}

	public boolean isFindByStatus() {
		return findByStatus;
	}

	public void setBegCreatedAt(Date begCreatedAt) {
		this.begCreatedAt = begCreatedAt;
	}

	public void setEndCreatedAt(Date endCreatedAt) {
		this.endCreatedAt = endCreatedAt;
	}

	public void setBegChangedAt(Date begChangedAt) {
		this.begChangedAt = begChangedAt;
	}

	public void setEndChangedAt(Date endChangedAt) {
		this.endChangedAt = endChangedAt;
	}

	public void setFindByName(String findByName) {
		this.findByName = findByName;
	}

	public void setFindByCnpj(String findByCnpj) {
		this.findByCnpj = findByCnpj;
	}

	public void setFindByEmail(String findByEmail) {
		this.findByEmail = findByEmail;
	}

	public void setFindByStatus(boolean findByStatus) {
		this.findByStatus = findByStatus;
	}

	public String getFindByCpf() {
		return findByCpf;
	}

	public void setFindByCpf(String findByCpf) {
		this.findByCpf = findByCpf;
	}

	public String getFindByLastName() {
		return findByLastName;
	}

	public void setFindByLastName(String findByLastName) {
		this.findByLastName = findByLastName;
	}

	public Date getBegExpireOn() {
		return begExpireOn;
	}

	public Date getEndExpireOn() {
		return endExpireOn;
	}

	public void setBegExpireOn(Date begExpireOn) {
		this.begExpireOn = begExpireOn;
	}

	public void setEndExpireOn(Date endExpireOn) {
		this.endExpireOn = endExpireOn;
	}

	public EquipmentTableCompInterface getEquipmentTable() {
		return equipmentTable;
	}

	public void setEquipmentTable(EquipmentTableCompInterface equipmentTable) {
		this.equipmentTable = equipmentTable;
	}

}
